package com.customization.unionpay.market.job;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.customization.unionpay.market.util.CloudFlashPaymentUtils;
import com.customization.unionpay.market.util.FormDataUtils;
import com.customization.unionpay.market.util.PropUtils;
import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;
import weaver.general.Util;
import weaver.integration.logging.Logger;
import weaver.integration.logging.LoggerFactory;
import weaver.interfaces.schedule.BaseCronJob;

import java.util.ArrayList;
import java.util.List;

/**
 * @author sjm
 * @description 定时根据授权码调用云闪付营销开放平台接口获取数据，营销预付活动台账活动未结束的同步活动出资金额，充值日期
 */
public class SyncMarketingPrepaidActivityLedgerByThirdJob extends BaseCronJob {

    private static final Logger log = LoggerFactory.getLogger(SyncMarketingPrepaidActivityLedgerByThirdJob.class);

    public void execute() {

        RecordSet rs = new RecordSet();

        try {
            // 营销预付活动台账表单id
            int marketingPrepaidActivityLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "marketing_prepaid_activity_ledger_form_id"));
            String isYes = FormDataUtils.getItemValue(marketingPrepaidActivityLedgerFormId, "cwsfjs", "是");
            String isNot = FormDataUtils.getItemValue(marketingPrepaidActivityLedgerFormId, "cwsfjs", "否");
            log.info("isNot：" + isNot);
            // 清算资金明细台账表单id
            int clearingFundDetailsLedgerFormId = Integer.parseInt(PropUtils.BB_LOG.getPropValue("marketSubject", "clearing_fund_details_ledger_form_id"));
            String clearingFundDetailTableName = FormDataUtils.getTableName(clearingFundDetailsLedgerFormId);
            log.info("clearingFundDetailTableName："+clearingFundDetailTableName);

            String maintablename = FormDataUtils.getTableName(marketingPrepaidActivityLedgerFormId);
            log.info("maintablename：" + maintablename);

            StringBuilder sql = new StringBuilder("select id,yxpthdsqm,cwsfjs from ");
            sql.append(maintablename);
            sql.append(" where cwsfjs = '");
            sql.append(isNot);
            sql.append("' ");

            log.info("查询sql:" + sql.toString());

            rs.executeQuery(sql.toString());

            List<String> codes = new ArrayList<>();
            while (rs.next()) {
                String yxpthdsqm = Util.null2String(rs.getString("yxpthdsqm"));
                if (!"".equals(yxpthdsqm)) {
                    if (!codes.contains(yxpthdsqm)) {
                        codes.add(yxpthdsqm);
                    }
                }
            }
            if(codes.size() > 0) {
                // 云闪付请求
                try {
                    String resultStr = CloudFlashPaymentUtils.batchQueryByBudgetAuthCode(codes);
                    log.info("返回参数：" + resultStr);

                    JSONObject resultJson = JSONObject.parseObject(resultStr);

                    String errorMessage = resultJson.getString("errorMessage");
                    if ("成功".equals(errorMessage)) {
                        JSONArray data = resultJson.getJSONArray("data");
                        log.info("解析data参数：" + data);
                        if(data.size() > 0){
                            for (int i = 0; i < data.size(); i++) {
                                JSONObject single = data.getJSONObject(i);
                                // 预算授权码
                                String budgetAuthCode = single.getString("budgetAuthCode");
                                log.info("budgetAuthCode:" + budgetAuthCode);
                                // 银联出资金额
                                String unionpayValueChecked = "".equals(single.getString("unionpayValueChecked")) ? "0" : single.getString("unionpayValueChecked");
                                log.info("unionpayValueChecked:" + unionpayValueChecked);
                                // 项目开始日期
                                String projectStartDateChecked = single.getString("projectStartDateChecked");
                                log.info("projectStartDateChecked:" + projectStartDateChecked);
                                // 同步资金账户类型
                                log.info("zjzhlx：" + single.getString("AcctType") );
                                Integer zjzhlx = single.getString("AcctType") == null ? 0 : (single.getInteger("AcctType")-1);
                                log.info("zjzhlx:" + zjzhlx);

                                RecordSetTrans rst = new RecordSetTrans();
                                // 开启事务（关闭自动提交）
                                rst.setAutoCommit(false);
                                try {
                                    // hdzxje  清算明细，sum 清算金额

                                    String clearDetailsSum = getClearDetailsSum(clearingFundDetailTableName, budgetAuthCode);

                                    if(clearDetailsSum == null || "".equals(clearDetailsSum)){
                                        clearDetailsSum = "0";
                                    }

                                    StringBuilder updateSql = new StringBuilder("update ");
                                    updateSql.append(maintablename);
                                    updateSql.append(" set hdczje='");
                                    updateSql.append(unionpayValueChecked);
                                    updateSql.append("',");
                                    updateSql.append("czrq='");
                                    updateSql.append(projectStartDateChecked);
                                    updateSql.append("',");
                                    updateSql.append("hdzxje='");
                                    updateSql.append(clearDetailsSum);
                                    updateSql.append("',");
                                    updateSql.append("zjzhlx='");
                                    updateSql.append(zjzhlx);
                                    updateSql.append("'  where yxpthdsqm = '");
                                    updateSql.append(budgetAuthCode);
                                    updateSql.append("' ");

                                    log.info("updateSql:" + updateSql.toString());
                                    // 活动出资金额，充值日期
                                    rst.executeUpdate(updateSql.toString());
                                    // 提交事务
                                    rst.commit();

                                } catch (Exception e) {
                                    // 回滚
                                    rst.rollback();
                                    log.error("修改数据异常：" + e.getMessage());
                                }
                            }
                        }else {
                            log.error("云闪付根据授权码查询为空！");
                        }
                    } else {
                        log.error("云闪付查询失败：" + resultJson.getString("errorCode") + "----" + resultJson.getString("errorMessage"));
                    }
                } catch (Exception e) {
                    log.error("云闪付请求异常：" + e.getMessage());
                }
            }else {
                log.error("查询营销预付活动台账活动未结项的授权码为空!");
            }
        } catch (Exception e) {
            log.error("定时任务异常：" + e.getMessage());
        }
    }

    /**
     * 根据活动授权码查询清算明细清算金额合计
     * @param tableName
     * @param actAuthCode
     * @return
     */
    private String getClearDetailsSum(String tableName,String actAuthCode){
        RecordSet rs = new RecordSet();
        try {
            StringBuilder sql = new StringBuilder("select sum(qsje) as qs from ");
            sql.append(tableName);
            sql.append(" where 1=1 and yxpthdsqm='");
            sql.append(actAuthCode);
            sql.append("' ");

            log.info("sql:"+sql.toString());
            rs.executeQuery(sql.toString());
            if (rs.next()) {
                return Util.null2String(rs.getString("qs"));
            }else {
                log.error("查询获取营销活动日报表台账数据异常!");
            }
        }catch (Exception e){
            log.error("查询异常："+e.getMessage());
        }
        return null;
    }
}

